/*
 * Copyright (c) 2022-2022 All rights Reserved.
 */

package com.driving.core.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.driving.core.base.BaseServiceImpl;
import com.driving.core.entity.Diary;
import com.driving.core.exception.DrivingException;
import com.driving.core.mapper.IDiaryMapper;
import com.driving.core.service.IDiaryService;
import com.driving.core.util.MessageType.ExceptionType;

/**
 * @author SAGITTAR
 * @since 2017
 */
@Service(value = "diaryService")
public class DiaryServiceImpl extends BaseServiceImpl<IDiaryMapper, Diary> implements IDiaryService {

    @Override
    public Map<String, Integer> recordDiary(Diary diary) {
        diary.setRecordDateTime(LocalDateTime.now());
        int diaryId = -1;
        if (retBool(baseMapper.insert(diary))) {
            diaryId = diary.getId();
        }
        Map<String, Integer> diaryMap = new HashMap<>(4);
        diaryMap.put("diaryId", diaryId);
        return diaryMap;
    }

    @Override
    public boolean diaryThumbUp(int diaryId) {
        Diary diary = baseMapper.selectById(diaryId);
        if (Objects.isNull(diary)) {
            throw new DrivingException(configReader.getExceptionMessage(ExceptionType.DATA_NOT_FOUND));
        }
        synchronized (Integer.toString(diaryId).intern()) {
            diary.setThumbUpCount(diary.getThumbUpCount() + 1);
            return retBool(baseMapper.updateById(diary));
        }
    }

    @Override
    public Map<String, Object> selectDiaryByOrder(String order, int currentPage) {
        // 参数转换
        String orderBy = null;
        if ("thumbUpCount".contentEquals(order)) {
            orderBy = "thumb_up_count";
        }
        if ("recordDateTime".contentEquals(order)) {
            orderBy = "record_date_time";
        }
        // 设置分页与查询
        Page<Map<String, Object>> mapPage = new Page<>(currentPage, 10);
        mapPage.addOrder(OrderItem.desc(orderBy));
        // 注意：这里一定要先查询再取变量，否则没有分页数据
        List<Map<String, Object>> diaryList = baseMapper.selectByOrder(mapPage);
        Map<String, Object> resultMapPage = new HashMap<>(6, 1);
        resultMapPage.put("totalPage", mapPage.getPages());
        resultMapPage.put("totalSize", mapPage.getTotal());
        resultMapPage.put("currentPage", mapPage.getCurrent());
        resultMapPage.put("pageSize", mapPage.getSize());
        resultMapPage.put("list", diaryList);
        return resultMapPage;
    }
}
